<?php
namespace Book\Controller;
use Think\Controller;
class AuthController extends Controller {
    public function register(){
        if(IS_POST){
            $info = I('post.');
            $userid = D('member')->register($info);
            
            //注册完直接登录
            session('userid',$userid);
            session('username',$info['username']);
                
            $cookie_time = 86400*30;
            cookie('username',$info['username'], $cookie_time);
            cookie('userid', $userid, $cookie_time);
            $data['redirect'] = '/';
            $this->ajaxReturn($data);
        }else{
            $this->display();
        }
    }

    public function login(){
        if(IS_POST){
            $info = I('post.');
            $username = $info['account'];
            $detail = D('Member')->where(['username' => $username])->find();
            if($detail){
                //记录session
                session('userid',$detail['userid']);
                session('username',$detail['username']);
                    
                $cookie_time = 86400*30;
                cookie('username',$username,$cookie_time);
                cookie('userid', $detail['userid'],$cookie_time);

                $data['redirect'] = '/';
                $this->ajaxReturn($data);
            }
            
        }else{
            $this->display();
        }
    }

    public function logout(){
        session(null);  // 清空当前的session
        cookie(null);
        redirect(U('auth/login'));
    }
}